<template>
  <div class="m-25 mt-65">
    <div class="normal-box-mod">
      <div class="normal-box-hd clearfix">
        <div class="normal-box-title">
          <div class="decorate-square"></div>
          <h2>模板管理</h2>
        </div>
      </div>
      <div class="normal-box-bd">
      <div class="normal-list-page-mod">
          <div class="normal-list-page-hd clearfix">
                <Button-group>
                  <Button custom-icon="iconfont icon-shanchusekuai" size="small" type="error" @click="batchDel">
                    删除
                  </Button>
                  <Button custom-icon="iconfont icon-fangkuai2" size="small" type="primary" @click="showCreateModal">
                    新建
                  </Button>
                </Button-group>
          </div>
          <div class="normal-list-page-bd">
              <Table border :loading="list.loading" :columns="list.columns" :data="list.tableData" @on-selection-change="selectionChange"></Table>
          </div>
          <div class="normal-list-page-ft clearfix">
              <Page class="fr" :total="queryData.totalRecord" :page-size="queryData.pageSize" :current="queryData.page" show-total @on-change="changePage" @on-page-size-change="onPageSizeChange" show-sizer></Page>
          </div>
      </div>

      <!--新建&修改-->
      <Modal v-model="modals.Entity.isShow" :loading="modals.Entity.loading" :mask-closable="false" :title="modals.Entity.title" @on-ok="postData">
        <Form ref="EntityFrom" :model="modals.Entity.formData" :rules="modals.Entity.rules" :label-width="120">
            <FormItem label="模板分组" prop="groupid">
                <Select v-model="modals.Entity.formData.groupid" style="width:200px">
                    <Option v-for="item in groupList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </FormItem>
            <FormItem label="前后端" prop="fbFlag">
                <Select v-model="modals.Entity.formData.fbFlag" style="width:200px">
                    <Option v-for="item in fbFlagObject" :value="item.id" :key="item.id">{{ item.name }}</Option>
                </Select>
            </FormItem>
          <FormItem label="模板名称" prop="name">
            <Input placeholder="请填模板名称" v-model="modals.Entity.formData.name" style="width:300px;"/>
          </FormItem>
            <FormItem label="模板模块" prop="codeFlag">
              <Select v-model="modals.Entity.formData.codeFlag" style="width:200px">
                <Option v-for="(item,index) in codeFlagObject" :value="item" :key="index">{{ item }}</Option>
              </Select>
            </FormItem>
            <FormItem label="模板内容" prop="content">
            <Input type="textarea" placeholder="请输入模板内容" v-model="modals.Entity.formData.content" style="width:300px;"/>
          </FormItem>
        </Form>
      </Modal>

</div>
</div>
  </div>
</template>
<script>
import {
  ajaxGetEntity,
  ajaxPostEntity,
  ajaxPutEntity,
  ajaxDelEntity
} from "@/api/generine/template.js";
import { ajaxGetAllEntity } from "@/api/generine/template_group.js";
import moment from "moment";
import { Message } from "iview";

export default {
  name: "Entity",
  data() {
    return {
      groupList: [],
      fbFlagObject: [{ id: 0, name: "后端" }, { id: 1, name: "前端" }],
      codeFlagObject: ["service", "serviceImpl", "controller", "front-api","front-vue"],
      // 弹出层数据
      modals: {
        Entity: {
          isShow: false,
          loading: true,
          type: "create", // create 新建，update 修改
          title: "新建",
          rules: {
            name: [
              {
                required: true,
                message: "请填分组名称",
                trigger: "blur"
              }
            ],
            groupid: [
              {
                required: true,
                message: "请选择模板分组",
                trigger: "blur",
                type: "number"
              }
            ],
            fbFlag: [
              {
                required: true,
                message: "请选择前后端",
                trigger: "blur",
                type: "number"
              }
            ],
            codeFlag: [
              {
                required: true,
                message: "请选择模块",
                trigger: "blur"
              }
            ],
            content: [
              {
                required: true,
                message: "请填写模板内容"
              }
            ]
          },
          formData: {
            id: undefined,
            name: "",
            memo: "",
            groupid: "",
            fbFlag: "",
            codeFlag: "",
            content: ""
          }
        }
      },
      // 列表
      list: {
        loading: false,
        selections: [],
        // 列表展示数据
        tableData: [],
        // 表格表头
        columns: [
          {
            type: "selection",
            minWidth: 60,
            align: "center"
          },
          // 开始自动生成
          {
            title: "ID",
            align: "center",
            key: "id",
            minWidth:100
          },
          {
            title: "模板名称",
            align: "center",
            key: "name",
            minWidth:100
          },
          {
            title: "前后端",
            key: "fbFlag",
            align: "center",
            minWidth:100,
            render: (h, params) => {
              if (params.row.fbFlag === 0) {
                return "后端";
              } else {
                return "前端";
              }
            }
          },
          {
            title: "模板标识",
            key: "codeFlag",
            align: "center",
            minWidth:100
          },
          {
            title: "模板分组",
            key: "groupid",
            align: "center",
            minWidth:100,
            render: (h, params) => {
              var result = "";
              for (var index in this.groupList) {
                if (this.groupList[index].id == params.row.groupid) {
                  result = this.groupList[index].name;
                  break;
                }
              }
              return result;
            }
          },
          {
            title: "创建时间",
            key: "crtTime",
            align: "center",
            minWidth:100,
            render: (h, params) => {
              let formatString = "YYYY-MM-DD HH:mm:ss";
              return moment
                .unix(params.row.crtTime / 1000)
                .format(formatString);
            }
          },
          {
            title: "更新时间",
            align: "center",
            key: "updTime",
            minWidth:100,
            render: (h, params) => {
              let formatString = "YYYY-MM-DD HH:mm:ss";
              return moment
                .unix(params.row.updTime / 1000)
                .format(formatString);
            }
          },
          // 自动生成结束
          {
            title: "操作",
            align: "center",
            minWidth: 130,
            render: (h, params) => {
              return h("div", { class: "action-group" }, [
                // h(
                //   "Button",
                //   {
                //     props: {
                //       type: "ghost",
                //       size: "small"
                //     },
                //     class: "mr-20",
                //     on: {
                //       click: () => {
                //         this.showUpdateModal(params.index);
                //       }
                //     }
                //   },
                //   [h("Icon", { props: { type: "edit", size: 14 } })]
                // ),
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'left',
                      content: '编辑'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'primary',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            this.showUpdateModal(params.index)
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-bianjisekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                ),
                
                h(
                  'Tooltip',
                  {
                    props: {
                      placement: 'right',
                      content: '删除'
                    },
                    style: {
                      cursor: 'pointer'
                    }
                  },
                  [
                    h(
                      'Button',
                      {
                        props: {
                          type: 'error',
                          size: 'small'
                        },
                        style: {
                          marginRight: '5px',
                          padding: '1px 2px'
                        },
                        on: {
                          click: () => {
                            this.delData([params.row.id])
                          }
                        }
                      },
                      [
                        h('Icon', {
                          props: {
                            type: ' iconfont icon-shanchusekuai',
                            size: 18
                          }
                        })
                      ]
                    )
                  ]
                )
                // h(
                //   "Button",
                //   {
                //     props: {
                //       type: "ghost",
                //       size: "small"
                //     },
                //     class: "",
                //     on: {
                //       click: () => {
                //         this.delData([params.row.id]);
                //       }
                //     }
                //   },
                //   [h("Icon", { props: { type: "trash-a", size: 14 } })]
                // )
              ]);
            }
          }
        ]
      },
      // 页面查询数据
      queryData: {
        limit: 10,
        page: 1,
        totalRecord: 0,
        name: ""
      }
    };
  },
  methods: {
    // 获取列表
    getTableData() {
      const that = this;
      that.queryData.totalRecord = undefined;
      ajaxGetEntity(that.queryData)
        .then(res => {
          that.list.tableData = res.data.list;
          that.queryData.totalRecord = res.totalRecord;
          that.queryData.page = res.pageNum;
          that.queryData.limit = res.pageSize;
          that.queryData.startDate = res.startDate;
          that.queryData.endDate = res.endDate;
        })
        .catch(error => {
          Message.error(error);
        });
    },

    // 新建&修改
    postData() {
      const that = this;
      that.$refs["EntityFrom"].validate(valid => {
        if (valid) {
          // 新建
          if (!that.modals.Entity.formData.id) {
            ajaxPostEntity(that.modals.Entity.formData)
              .then(res => {
                that.modals.Entity.isShow = false;
                that.modals.Entity.loading = false;
                if (!res.code) {
                  that.getTableData();
                  that.$Notice.success({
                    title: "保存成功!"
                  });
                } else {
                  that.$Notice.error({
                    title: res.message
                  });
                }
              })
              .catch(error => {
                Message.error(error);
              });
          } else {
            // 修改
            ajaxPutEntity(
              that.modals.Entity.formData.id,
              that.modals.Entity.formData
            )
              .then(res => {
                that.modals.Entity.isShow = false;
                that.modals.Entity.loading = false;
                if (!res.code) {
                  that.getTableData();
                  that.$Notice.success({
                    title: "保存成功!"
                  });
                } else {
                  that.$Notice.error({
                    title: res.message
                  });
                }
              })
              .catch(error => {
                Message.error(error);
              });
          }
        } else {
          that.modals.Entity.loading = false;
          that.$nextTick(() => {
            that.modals.Entity.loading = true;
          });
        }
      });
    },

    // 删除
    delData(ids) {
      if (!ids.length) {
        return;
      }
      // const _id = JSON.parse(JSON.stringify(this.list.tableData))[index].id;
      this.$Modal.confirm({
        title: "确认删除",
        content:
          "<p>您确认删除id为 <strong>" +
          ids.toString() +
          "</strong> 的记录吗?</p><p>删除后将无法撤销，请谨慎操作！</p>",
        loading: true,
        onOk: () => {
          ajaxDelEntity({
            ids: ids
          }).then(res => {
            this.$Modal.remove();
            if (!res.code) {
              this.$Notice.success({
                title: "删除成功"
              });
              this.queryData.pageNum = 1;
              this.getTableData();
            } else {
              this.$Notice.error({
                title: res.message
              });
            }
          });
        }
      });
    },

    // 排量删除
    batchDel() {
      let ids = [];
      this.list.selections.forEach(element => {
        ids.push(element.id);
      });
      if (!ids.length) {
        this.$Message.error({
          content: "请先选择要删除的项！",
          duration: 3
        });
      }
      this.delData(ids);
    },
    getTemplateGroup() {
      const that = this;
      that.queryData.totalRecord = undefined;
      ajaxGetAllEntity(that.queryData)
        .then(res => {
          that.groupList = res.data;
        })
        .catch(error => {
          Message.error(error);
        });
    },

    // 全选，不全选
    selectionChange(args) {
      this.list.selections = args;
    },
    //每页显示记录数变更
    onPageSizeChange(pageSize) {
      this.queryData.pageSize = pageSize;
      this.getTableData();
    },
    // 换页
    changePage(page) {
      this.queryData.pageNum = page;
      this.getTableData();
    },
    //改变开始时间
    changeStartDate(date) {
      this.queryData.startDate = date;
    },
    //改变结束时间
    changeEndDate(date) {
      this.queryData.endDate = date;
    },
    // 查找
    goSearch() {
      this.getTableData();
    },

    // 显示新建弹窗
    showCreateModal() {
      this.modals.Entity.type = "create";
      this.modals.Entity.title = "新建";
      this.modals.Entity.formData = {
        // 以下自动生成
        id: undefined,
        title: "",
        author: ""
        // 自动生成结束
      };
      this.modals.Entity.isShow = true;
    },

    // 显示修改弹窗
    showUpdateModal(index) {
      this.modals.Entity.type = "update";
      this.modals.Entity.title = "修改";
      this.modals.Entity.formData = JSON.parse(
        JSON.stringify(this.list.tableData)
      )[index];
      this.modals.Entity.isShow = true;
    }
  },
  created() {
    this.getTableData();
    this.getTemplateGroup();
  }
};
</script>
